package org.unit.testmgmt.ui.table;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

public class TableEntryList<T extends ITableEntry> {

	private final int COUNT = 10;
	private Vector<T> tblEntryList = new Vector<T>(COUNT);
	private Set<ITableEntryListListener> changeListeners = new HashSet<ITableEntryListListener>();
	private Class<T> clazz;
	private TableViewerColumns tblViewerColumns = null;

	public TableEntryList(Class<T> clazz, TableViewerColumns tblViewerColumns) {
		this(clazz);
		this.tblViewerColumns = tblViewerColumns;
	}

	/**
	 * Constructor
	 */
	public TableEntryList(Class<T> clazz) {
		super();
		this.clazz = clazz;
	}

	public T createTableEntry(boolean addToList) {
		T tblEntry;
		try {
			tblEntry = clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(
					"Error while instantiation of table-entry! Class: "
							+ clazz.getName());
		}

		if (tblViewerColumns != null)
			tblEntry.setTableViewerColumns(tblViewerColumns);

		if (addToList)
			addTableEntry(tblEntry);

		return tblEntry;
	}

	public T createTableEntry() {
		return createTableEntry(true);
	}

	/**
	 * Return the collection of tasks
	 */
	public Vector<T> getTableEntries() {
		return tblEntryList;
	}

	/**
	 * Add a new task to the collection of tasks
	 */
	public void addUncheckedTableEntry(ITableEntry tblEntry) {
		@SuppressWarnings("unchecked")
		T tblEntryTyped = (T) tblEntry;
		addTableEntry(tblEntryTyped);
	}

	/**
	 * Add a new task to the collection of tasks
	 */
	public void addTableEntry(T tblEntry) {
		tblEntryList.add(tblEntryList.size(), tblEntry);
		Iterator<ITableEntryListListener> iterator = changeListeners.iterator();
		while (iterator.hasNext())
			((ITableEntryListListener) iterator.next()).addTableEntry(tblEntry);
	}

	/**
	 * @param task
	 */
	public void removeTableEntry(ITableEntry tblEntry) {
		tblEntryList.remove(tblEntry);
		Iterator<ITableEntryListListener> iterator = changeListeners.iterator();
		while (iterator.hasNext())
			((ITableEntryListListener) iterator.next())
					.removeTableEntry(tblEntry);
	}

	/**
	 * @param tblEntry
	 * @param value
	 * @param column
	 * @param oldValue
	 */
	public void tableEntryChanged(ITableEntry tblEntry,
			TableViewerColumn column, Object value, Object oldValue) {
		Iterator<ITableEntryListListener> iterator = changeListeners.iterator();
		while (iterator.hasNext())
			((ITableEntryListListener) iterator.next()).updateTableEntry(
					tblEntry, column, value, oldValue);
	}

	/**
	 * @param viewer
	 */
	public void removeChangeListener(ITableEntryListListener viewer) {
		changeListeners.remove(viewer);
	}

	/**
	 * @param viewer
	 */
	public void addChangeListener(ITableEntryListListener viewer) {
		changeListeners.add(viewer);
	}
}
